package com.jingzhongbao.concurrent.lock;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * User:jzb
 * Date:2018/11/15 Time:12:44 
 * 篮子 生产者和消费者需要向篮子申请锁
 */
public class Bucket {
	/**
	 * 蓝子
	 */
	private List<String> buckets;

	/**
	 * 蓝子的容量
	 */
	private final int maxCount = 20;

	/**
	 * 蓝子上的锁
	 */
	private final Lock lock = new ReentrantLock();

	/**
	 * 消费锁对象
	 */
	private final Condition fetchLock;

	/**
	 * 生产锁对象
	 */
	private final Condition addLock;

	public Bucket() {
		buckets = new ArrayList<>();
		fetchLock = lock.newCondition();
		addLock = lock.newCondition();
	}

	/**
	 * 获得锁
	 * 
	 * @return
	 */
	public Lock getLock() {
		return lock;
	}

	/**
	 * 获得消费锁对象
	 * 
	 * @return
	 */
	public Condition getFetchLock() {
		return fetchLock;
	}

	/**
	 * 获得生产锁对象
	 * 
	 * @return
	 */
	public Condition getAddLock() {
		return addLock;
	}

	/**
	 * 蓝子当前大小
	 * 
	 * @return
	 */
	public int size() {
		return buckets.size();
	}

	/**
	 * 放入
	 * 
	 * @param obj
	 */
	public boolean add(String obj) {
		if (buckets.size() < maxCount) {
			buckets.add(obj);
			return true;
		} else
			return false;
	}

	/**
	 * 随机获取一个蓝子里的东西
	 * 
	 * @return
	 */
	public String fetch() {
		int size = buckets.size();
		if (size == 1) {
			String obj = buckets.get(0);
			buckets.clear();
			return obj;
		} else if (size > 1) {
			int index = new Random().nextInt(size);
			String obj = buckets.get(index);
			buckets.remove(index);
			return obj;
		} else
			return null;
	}
}
